package com.webserver.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * 负责与指定客户端进行一次HTTP交互
 * HTTP协议要求客户端与服务端采取一问一答的交互规则.
 * 并在交互完毕后断开TCP连接
 *
 * 因此,这里处理一次HTTP交互采取的过程分为三部分:
 * 1:解析请求(读取客户端发送过来的HTTP请求内容)
 * 2:处理请求(分析请求信息确定客户端意图,并进行对应的处理)
 * 3:发送响应(给浏览器发送一个HTTP中的响应,将处理结果回复给浏览器)
 */
public class ClientHandler implements Runnable{

    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    public void run(){
        try {
            InputStream in = socket.getInputStream();
            int d;
            StringBuilder builder = new StringBuilder();
            char cur = 'a', pre = 'a';
            while ((d = in.read())!=-1){
                cur = (char)d;
                if(pre == 13 && cur == 10){
                    break;
                }
                builder.append(cur);
                pre = cur;
            }
            String line = builder.toString().trim();
            System.out.println("请求行内容"+line);
            //请求行相关信息
            String method;//请求方式GET
            String uri;//抽象路径/string/ds
            String protocol;//协议版本HTTP/1.1


            String[] a = line.split("\\s");
            method = a[0];
            uri = a[1];
            protocol = a[2];
            System.out.println("method:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //交互后语客户端断开连接
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
